﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Snowy.Data;
using Snowy.Dtos;
using Snowy.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Snowy.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private UserService _user;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ApplicationDbContext _dbContext;

        public LoginController(UserService user, IHttpContextAccessor httpContextAccessor, ApplicationDbContext dbContext)
        {
            _user = user;
            _httpContextAccessor = httpContextAccessor;
            _dbContext = dbContext;
        }
        
        [HttpPost()]
        public ActionResult Login( LoginDto   dto)
        {

            var user = from u in _dbContext.SysUsers where u.Account == dto.Account && dto.Password == u.Password select u;
            if (user.Any())
            {
                var u = user.FirstOrDefault();
                var refreshToken = _user.generateJwtToken(u);
               _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken.access_token;
                return Ok(new ApiResult<string>(ApiCode.Success, refreshToken.access_token));
            }
            else
            {
                return Unauthorized();
            }
        }

    }
}
